#include "Alice/Systems/SpriteAnimRenderSys.h"
#include "Alice/Components/SpriteAnimComp.hpp"
#include "Alice/Components/TransformComp.hpp"
#include "Alice/Components/ColorComp.hpp"
#include "Alice/Core/World.h"

namespace Alice
{

void SpriteAnimRenderSys::Before()
{
    m_clip_texture_renderer.Init();
    // 初始化所有动画的数据
    for (auto entity : entitys)
    {
        SpriteAnimComp& SA_comp = world->GetComp<SpriteAnimComp>(entity);
        SA_comp.current_frame = 0;
        SA_comp.previous_time = 0.0;
    }
}

void SpriteAnimRenderSys::OnUpdate()
{
    for (auto entity : entitys)
    {
        Scene& current_scene = world->GetCurrentScene();
        if (current_scene.entitys.find(entity) == 
            current_scene.entitys.end())
        {
            continue;
        }

        ColorComp& color_comp = world->GetComp<ColorComp>(entity);
        TransformComp& tf_comp = world->GetComp<TransformComp>(entity);
        SpriteAnimComp& SA_comp = world->GetComp<SpriteAnimComp>(entity);
        Timer& timer = world->GetTimer();

        // 计算出当前帧在纹理中的位置
        int frame_num = SA_comp.current_frame + SA_comp.head_frame;

        m_clip_texture_renderer.Render(
            SA_comp.texture,
            tf_comp.position,
            tf_comp.size,
            tf_comp.rotate,
            color_comp.color,
            SA_comp.width,
            SA_comp.height,
            frame_num
        );

        double current_time = timer.CurrentTime();
        if (current_time - SA_comp.previous_time >= SA_comp.rate)
        {
            SA_comp.current_frame += 1;
            if (SA_comp.current_frame > SA_comp.frame_total)
            {
                SA_comp.current_frame %= SA_comp.frame_total;
            }
            
            SA_comp.previous_time = current_time;
        }
    }
}

void SpriteAnimRenderSys::After()
{
    m_clip_texture_renderer.Destroy();
}

} // namespace Alice
